In [21]:
import re
import itertools
from collections import defaultdict
_PARSER = re.compile("([a-zA-Z]+) to ([a-zA-Z]+) = ([0-9]+)")
def load_distances(distances):
city_distances = defaultdict(dict)
for d in distances:
c_from, c_to, kms = _PARSER.match(d.strip()).groups()
city_distances[c_from][c_to] = kms
city_distances[c_to][c_from] = kms
return city_distances
def count_distance(distances, route):
p = route[0]
kms = 0
for c in route[1:]:
kms += int(distances[p][c])
p = c
return kms
def find_route(distances, shortest=True):
city_distances = load_distances(distances)
all_cities = list(city_distances.keys())
min_route = tuple(all_cities)
min_distance = count_distance(city_distances, min_route)
for route in itertools.permutations(city_distances.keys()):
kms = count_distance(city_distances, route)
if (shortest and kms < min_distance) or (not shortest and kms > min_distance):
min_route = route
min_distance = kms
return min_route, min_distance
In [22]:
%%time
# Test example
example = ["London to Dublin = 464","London to Belfast = 518","Dublin to Belfast = 141"]
print(find_route(example))
In [23]:
%%time
# Check input
with open('day9/input.txt', 'rt') as fd:
print(find_route(fd))
In [24]:
%%time
# Test example
example = ["London to Dublin = 464","London to Belfast = 518","Dublin to Belfast = 141"]
print(find_route(example, shortest=False))
In [25]:
%%time
# Check input
with open('day9/input.txt', 'rt') as fd:
print(find_route(fd, shortest=False))
In [ ]: